
package com.roc.web.action.terminal;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.SnReleaseBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IPagenitionService;
import com.roc.service.transReport.SnReleaseService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@SuppressWarnings("serial")
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/snRelease")
public class SnReleaseAction extends PaginationBaseAction {
	private Logger logger=LogManager.getLogger(SnReleaseAction.class);

	@Autowired
	IPagenitionService pagenitionService;
	@Autowired
	IPageService pageService1;
	
	private SnReleaseSearchCondition searchCondition;
	@Autowired
	private SnReleaseService snReleaseService;
	
	private SnReleaseBean snList;
	/**
	 * 
	 * SN释放主页面
	 * @Title: init
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/terminal/SnReleaseQuery.jsp")
    })
	public String init(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
			addActionError("当前登录账号无权限访问!!!");
			return ERROR;
		}
		return SUCCESS;
	}
	/*	Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(op.getRoleType().equals(Role.CLEAR_LEAD.getCode()) || 
			    op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())||
			    op.getRoleType().equals(Role.SYSTEM.getCode())) {
			
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
		}*/
		
	
	/**
	 * SN释放查询
	 * @Title: querySnRelease
	 * @Description: TODO
	 * @param @return    
	 * @return String    
	 * @throws
	 */
	@Action(value="querySnRelease",results={@Result(name=SUCCESS,location="/pages/terminal/SnReleaseQuery.jsp"),
			@Result(name = ERROR, location = "/error.jsp")})
	public String querySnRelease(){
		 Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			if(op.getRoleType().equals(Role.AGENT.getCode())&&!"sdsyb".equals(op.getAccountNo())) {
				addActionError("当前登录账号无权限访问!!!");
				return ERROR;
			}
         try {
        	
        	 if(searchCondition==null){
        		 searchCondition=(SnReleaseSearchCondition)getSearchConditionFromSession();
					if(searchCondition==null){
						searchCondition=new SnReleaseSearchCondition();
					}
			}
					
//			if(op.getRoleType().equals(Role.CLEAR_LEAD.getCode()) || 
//			    op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())||
//			    op.getRoleType().equals(Role.SYSTEM.getCode())  ){
				
				int rows=pagenitionService.countSQL(searchCondition);
				if(rows>0){
					searchRsList=pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				}else if(rows==0){
					if(searchCondition.getDeviceCd()!=null&&!"".equals(searchCondition.getDeviceCd())){
						 int resu = snReleaseService.NoSnRelease(op,searchCondition);
						if(resu>0){
							addActionMessage("SN释放成功!");
						}else{
							addActionMessage("SN释放失败!");
						}
					}
					
				}
				List<SnReleaseBean> SnList = new ArrayList<SnReleaseBean>();	
				if(searchRsList.size()>0 && searchRsList!=null){			
					Iterator<?> iterator=searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj= (Object[])iterator.next();
						SnReleaseBean snb = new SnReleaseBean();
						snb.setMchtCd(Constance.Null2EmptyTrim(obj[0]));  //商户号
						snb.setNameBusi(Constance.Null2EmptyTrim(obj[1])); //商户名称
						snb.setAgentName(Constance.Null2EmptyTrim(obj[2])); //所属代理商
						snb.setOneAgent(Constance.Null2EmptyTrim(obj[3]));   //一级道理上
						snb.setTermTp(Constance.Null2EmptyTrim(obj[4]));     //终端类型
						snb.setTermId(Constance.Null2EmptyTrim(obj[5]));     //终端编号
						snb.setDeviceCd(Constance.Null2EmptyTrim(obj[6]));    //终端设备序列号
						snb.setInstalllocation(Constance.Null2EmptyTrim(obj[7]));//安装位置
						SnList.add(snb);
					}
				}
				
				getRequest().setAttribute("SnList", SnList);
				this.setTotalPage(this.calcuTotalPage(rows));
				getRequest().setAttribute(SEARCH_RS_LIST, SnList);
				getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
				getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
				setSearchToConditionSession(searchCondition);
				addActionMessage("当前条件下统计到【"+rows+"】条记录");
//					}
         }catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
		
	}
	@Action(value="SnRelease",results={@Result(name=SUCCESS,location="/pages/terminal/SnReleaseQuery.jsp"),
			@Result(name = ERROR, location = "/error.jsp")})
	public String SnRelease(){
		Operators op = (Operators) getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		PrintWriter pw = null;
		try {
			
			JSONObject json = JSONObject.fromObject(snList.getDeviceCd());
			getResponse().setCharacterEncoding("utf-8");
			pw = getResponse().getWriter();
			logger.info(op.getRealName()+"开始释放SN,释放的数据为："+json);
			
			boolean boo  = snReleaseService.SnRelease(op, json);
			if(!boo){
				json.put("msg", "释放失败,SN有强扣记录！");
				json.put("boo", boo);
			}else{
				json.put("msg", "SN释放成功");
				json.put("boo", boo);
			}
			pw.write(json.toString());
				
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			logger.info("释放SN失败！！！");
			addActionError(e.getMessage());
			return ERROR;
		}finally{
			if(pw != null){
				pw.close();
			}
		}
		
		return SUCCESS;
	}
	
	
	
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}


	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);

	}


	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_BEAN_TERMINAL_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE+"";
	}
	
	
	public SnReleaseSearchCondition getSearchCondition() {
		return searchCondition;
	}
	public void setSearchCondition(SnReleaseSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	public SnReleaseBean getSnList() {
		return snList;
	}
	public void setSnList(SnReleaseBean snList) {
		this.snList = snList;
	}



	

}
